package com.xyu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xyu.common.constant.ProductConstant;
import com.xyu.common.to.SkuEsModel;
import com.xyu.gulimall.product.feign.SearchFeignService;
import com.xyu.gulimall.product.feign.WareFeignService;
import com.xyu.gulimall.product.to.SkuReductionTo;
import com.xyu.gulimall.product.to.SpuBoundTo;
import com.xyu.common.utils.R;
import com.xyu.gulimall.product.entity.*;
import com.xyu.gulimall.product.feign.CouponFeignService;
import com.xyu.gulimall.product.service.*;
import com.xyu.gulimall.product.spuvo.*;
import com.xyu.gulimall.product.vo.AttrRespVo;
import com.xyu.gulimall.product.vo.SkuHasStockVo;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyu.common.utils.PageUtils;
import com.xyu.common.utils.Query;

import com.xyu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品
     * // TODO 高级部分完善其他内容
     *
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1，保存spu基本信息 pms_spu_info
        //创建对应数据库中pms_spu_info的实体类
        /**
         * 保存spu基本信息  pms_spu_info   1
         */
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //将从接收请求的参数与之对应copy一份
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        //没有传递时间，当前时间需要手动设置
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        //保存基本信息
        this.saveBaseSpuInfo(spuInfoEntity);
        System.out.println("基本信息保存成功");
        Long SpuId = spuInfoEntity.getId();
        System.out.println("SpuId" + SpuId);
        //====================================

        /**
         * 保存spu描述信息  pms_spu_info_desc  2
         */
        //2，保存spu的描述图片 pms_spu_info_desc
        //获取描述信息
        List<String> decript = spuSaveVo.getDecript();
        //创建pms_spu_info_desc对应实体类
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        //获取从接收参数copy的实体类的id
        descEntity.setSpuId(SpuId);
        //获取描述信息 Spring.join拼接list为字符串
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //保存描述信息
        System.out.println("spu图片保存成功");
        //=======================================================
        /**
         * 保存spu图片信息 pms_spu_images   3
         */
        System.out.println("getId：" + spuInfoEntity.getId());
        //3，保存spu图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(SpuId, images);
        System.out.println("spu图片信息保存成功");
        //========================================================
        /**
         * 保存spu规格参数  pms_product_attr_value 4
         */
        //4，保存spu规格参数 pms_product_attr_value
        //获取所有规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        //收集到对应实体类中，收集成list
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            //将对应VO实体类对象的属性copy到与数据库对应的实体类中，没用BeanUtils.copyProperties();因为只有三个属性对应
            //spu_id
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            //attr_id
            attrValueEntity.setAttrId(item.getAttrId());
            AttrRespVo attrInfo = attrService.getAttrInfo(item.getAttrId());
            //attr_name
            attrValueEntity.setAttrName(attrInfo.getAttrName());
            //attr_value
            attrValueEntity.setAttrValue(item.getAttrValues());
            //quick_show
            attrValueEntity.setQuickShow(item.getShowDesc());
            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);
        System.out.println("规格参数保存成功");


        /**
         * 远程调用gulimall-coupon 保存spu积分信息 sms_spu_bounds 5
         */
        //5，保存spu的积分信息 gulimall_sms -> sms_spu_bounds
        //创建bounds获取优惠券,积分...
//        Bounds bounds = new Bounds();
        Bounds bounds = spuSaveVo.getBounds();
        //创建数据传输对象
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        //将VO实体类中的数据copy到数据传输对象实体类中
        BeanUtils.copyProperties(bounds, spuBoundTo);
        //将spu_id也放到数传输对象实体类中
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R save = couponFeignService.save(spuBoundTo);
        if (save.getCode() != 0) {
            log.error("远程积分信息保存失败");
        } else {
            System.out.println("远程保存成功 积分信息");
        }
        //========================================
        /**
         * sku
         */

        //6，保存当前spu对应的所有sku信息
        //1，sku的基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                /**1，sku的基本信息 pms_sku_info 6
                 *     private String skuName;
                 *     private BigDecimal price;
                 *     private String skuTitle;
                 *     private String skuSubtitle;
                 *     相同字段
                 */
                //遍历出默认图片
                String defaultImage = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                //copy
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                //保存sku基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);
                System.out.println("sku基本信息保存成功");
                //=======================================
                /** pms_sku_images 7
                 * 保存sku图片信息
                 */
                //2，sku的图片信息 pms_sku_images

                //保存完之后获取保存的sku自增主键 通过sku_id保存sku图片信息
                //保存完之后获取保存的sku自增主键 通过sku_id保存sku图片信息
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imageEntity = item.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());

                    return skuImagesEntity;
                }).filter(entity -> {
                    //过滤 过滤出为true的
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //2，sku的图片信息 pms_sku_images
                if (imageEntity.size() == 0) {
                    System.out.println("Sku的id查询" + skuId);
                    System.out.println("imageEntity中没有图片");
                }
                skuImagesService.saveBatch(imageEntity);
                System.out.println("sku图片保存成功");
                //TODO 没用图片：路径无需保存
                //======================================
                /**
                 * 保存sku销售属性信息  8
                 * 表名 pms_sku_sale_attr_value
                 */
                //3，sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValue = attr.stream().map(skuSale -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(skuSale, skuSaleAttrValueEntity);
                    //设置sku_id
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //保存销售属性
                skuSaleAttrValueService.saveBatch(skuSaleAttrValue);
                System.out.println("销售属性保存成功");
                //====================================
                /**
                 * 远程调用gulimall-coupon 保存优惠，满减
                 */
                //4，sku的优惠，满减等信息 guilimall_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                //创建数据传输对象SkuReductionTo
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                //将Skus中的对应数据copy到数据传输对象中
                BeanUtils.copyProperties(item, skuReductionTo);
                //memberprice存到里面
                /**
                 * 报错 memberprice 没有赋值
                 */
                //将sku_id也保存到里面
                skuReductionTo.setSkuId(skuId);
                //调用远程接口保存                              compareTO 比较有三个返回值如果大于返回1，如果小于返回-1，如果等于返回0
                //满减和优惠不是一张表，所以要用or
                System.out.println("远程调用=====" + skuReductionTo.toString());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    } else {
                        System.out.println("远程调用sku保存成功");
                    }
                }
            });
        }
    }

    //保存spu基本信息
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * Spu检索操作
     * @param params
     * @return
     */
    /**
     * 判断参数
     * key: '华为',//检索关键字
     * catelogId: 6,//三级分类id
     * brandId: 1,//品牌id
     * status: 0,//商品状态
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            /**
             * 需要用and 不然字符串拼接
             * 如果不用and的话 id spu_name 有一个成立后面的比对就失效了
             * 加上wrapper.and 则是这样的(id=key or spu_name=key) and catalog_id=catelog_id and..
             */
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
//            wrapper.and(i ->{i.eq("catalog_id",catelogId);});
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        List<SkuEsModel> uoProduct = new ArrayList<>();
        //组装需要的数据
        SkuEsModel skuEsModel = new SkuEsModel();
        //1，查出当前spuId对应的sku信息 品牌的名字 pms_sku_info
        List<SkuInfoEntity> skuBySpuId = skuInfoService.getSkuBySpuId(spuId);
        //获取skuId
        List<Long> skuIdList = skuBySpuId.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // TODO 4, 查询当前sku的所有规格属性
        List<ProductAttrValueEntity> attrValueEntitie = productAttrValueService.AttrListSpu(spuId);
        //封装attr_id
        List<Long> collect1 = attrValueEntitie.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //通过attr_id查询可以检索的记录
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(collect1);

        //根据返回的searchAttrIds过滤掉不需要检索的记录
        List<SkuEsModel.Attrs> productAttr = attrValueEntitie.stream().filter(item -> {
            return searchAttrIds.contains(item.getAttrId());
        }).map(item ->{
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item,attrs);
            return attrs;
        }).collect(Collectors.toList());
        Map<Long, Boolean> HasStock = null;

        // TODO 远程调用异常处理
        try{
            // TODO 1, 发送远程调用，库存系统查询是否有库存
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            //获取结果
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            HasStock = skuHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,SkuHasStockVo::getHasStock));

        }catch (Exception e){
            log.error("远程调用发生异常{"+e+"}");
        }

        //封装每个sku的信息
        Map<Long, Boolean> finalHasStock = HasStock;
        List<SkuEsModel> upProducts = skuBySpuId.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            /*
            对拷不一样的字段SkuEsModel SkuInfoEntity实体类 price skuPrice ，skuDefaultImg skuImg
            单独查询 库存 hasStock 热度评分 hotScore
            品牌名字 brandName 品牌图片 brandImg 商品名字
            attrs类 attrId attrName attrValue
             */
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            esModel.setHasStock(true);
            // TODO 2, 热度评分 默认 0 暂时赋值为0
            esModel.setHotScore(0L);
            // TODO 3, 品牌和分类的名字
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());
            //设置检索属性
            esModel.setAttrs(productAttr);
            //设置库存情况
            if(finalHasStock == null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalHasStock.get(sku.getSkuId()));
            }
            return esModel;
        }).collect(Collectors.toList());

        System.out.println(upProducts);
        // TODO 5, 将数据发送给es进行保存 gulimall-search 检索服务
        R r = searchFeignService.ProductStatusUp(upProducts);
        if(r.getCode()==0){
            //发布成功操作
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            //上架商品
            spuInfoEntity.setPublishStatus(ProductConstant.StatusEnum.UP_SPU.getCode());
            //更新时间
            spuInfoEntity.setUpdateTime(new Date());
            int id = baseMapper.update(spuInfoEntity, new UpdateWrapper<SpuInfoEntity>().eq("id", spuInfoEntity.getId()));
            System.out.println("上架成功");
        }else{
            //发布失败操作
            log.error("上架失败");
            // TODO 遗留问题，重复调用，也就是接口幂等性 重试机制
        }
    }


}
